package com.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.common.dto.CategoryDTO;
import com.common.exception.ModelCoverDTOFailedException;
import com.common.exception.ModelNotFoundException;
import com.common.mapper.CategoryMapper;
import com.common.model.Category;
import com.common.query.CategotyQueryParam;
import com.common.service.ArticleService;
import com.common.service.CategoryService;
import com.util.CombineBeansUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@Service
public class CategoryServiceImpl implements CategoryService {

    private CategoryMapper categoryMapper;

    @Resource
    private ArticleService articleService;

    public CategoryServiceImpl(CategoryMapper categoryMapper) {
        this.categoryMapper = categoryMapper;
    }

    @Override
    public IPage<Category> selectPage(Integer page, Integer pageSize) {

        QueryWrapper<Category> qw = new QueryWrapper<>();
        qw.orderBy(true, false, "category_id");

        return categoryMapper.selectPage(new Page<>(page, pageSize), qw);
    }

    @Override
    public List<CategoryDTO> selectAllCategory() {

        CategotyQueryParam cqp = new CategotyQueryParam();
        cqp.setOrder("category_id");
        cqp.setSort("desc");

        List<Category> categories = categoryMapper.selectAllCategoryByQuery(cqp);
        List<CategoryDTO> categoryDTOS = new LinkedList<>();
        categories.forEach(category -> {
            try {
                categoryDTOS.add(coverEntityToDTO(category));
            } catch (InvocationTargetException | IllegalAccessException e) {
                throw new ModelCoverDTOFailedException();
            }
        });
        return categoryDTOS;
    }

    @Override
    public CategoryDTO selectById(Long id) {

        Category category = categoryMapper.selectById(id);

        if (category == null) {
            throw new ModelNotFoundException();
        } else {
            try {
                return coverEntityToDTO(category);
            } catch (InvocationTargetException | IllegalAccessException e) {
                throw new ModelCoverDTOFailedException();
            }
        }
    }

    @Override
    public int insert(Category category) {

        if (category.getCreateTime() == null) {
            category.setCreateTime((int) (System.currentTimeMillis() / 1000));
        }

        return categoryMapper.insert(category);
    }

    @Override
    public int delete(Long categoryId) {

        Category category = categoryMapper.selectById(categoryId);
        //找不到要删除的类
        if (category == null) {
            throw new ModelNotFoundException();
        }

        return categoryMapper.deleteById(categoryId);
    }

    @Override
    public int update(Long categoryId, Category category) {

        Category oldCategory = categoryMapper.selectById(categoryId);

        if (oldCategory == null) {
            throw new ModelNotFoundException();
        }

        try {
            CombineBeansUtil.combineBean(category, oldCategory);
        } catch (InvocationTargetException | IllegalAccessException e) {
            throw new ModelCoverDTOFailedException();
        }

        return categoryMapper.updateById(oldCategory);
    }

    @Override
    public Map<Long, String> searchCategoryList(String title) {

        QueryWrapper<Category> qw = new QueryWrapper<>();
        qw.orderBy(true, false, "category_id");
        if (title != null) {
            qw.like("title", title);
        }

        List<Category> categories = categoryMapper.selectList(qw);
        Map<Long, String> result = new HashMap<>();
        categories.forEach(category -> result.put(category.getCategoryId(), category.getTitle()));

        return result;
    }


    private CategoryDTO coverEntityToDTO(Category category) throws InvocationTargetException, IllegalAccessException {
        CategoryDTO categoryDTO = new CategoryDTO();
        CombineBeansUtil.combineBean(category, categoryDTO);
        categoryDTO.setArticleNum(articleService.countByCategoryId(categoryDTO.getCategoryId()));
        return categoryDTO;
    }

}
